package com.cluster.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * 请求权限验证
 */
public class RequestInterceptor implements HandlerInterceptor {

    private static Logger logger = LoggerFactory.getLogger(RequestInterceptor.class);

    /**
     * 之前执行（进入Handler处理之前）
     * 可以进行权限验证
     * @param request
     * @param response
     * @param handler
     * @return  true放行，false中止程序
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        logger.info("=============进入到拦截器==============");
        logger.info("获取到的sessionId:{}, session信息:{}", session.getId(), session.toString());
        Enumeration<String> attrs = session.getAttributeNames();
        logger.info("=============遍历session中的键值对信息>>>开始==============");
        // 遍历attrs中的
        while(attrs.hasMoreElements()){
            // 获取session键值
            String name = attrs.nextElement();
            // 根据键值取session中的值
            Object value = session.getAttribute(name);
            logger.info("session键值:{}, session的value值:{}", name, value);
        }
        logger.info("=============遍历session中的键值对信息>>>结束==============");
        logger.info("==============>>>当前访问url:{}", request.getRequestURI());
        Object usernameSession = session.getAttribute("username");
        logger.info("获取session中的usernameSession信息:{}", usernameSession);
        if (usernameSession == null) {
            // 没有登录,重定向到登录页
            logger.info("如果从session中获取的username为null, 则未登录, 请登录, 重定向到/login/toLogin登录页面!");
            response.sendRedirect(request.getContextPath() + "/login/toLogin");
            return false;
        } else {
            // 已登录，放行
            logger.info("如果从session中获取的usernameSession信息:{}, 不为null, 则已登录, 放行请求!", usernameSession);
            return true;
        }
    }

    /**
     * 之中执行（Handler处理完毕但尚未跳转页面）
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * 之后执行（Handler处理完毕而且已经跳转页面）
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
